package com.clusterswisdom.horn.api.tmall.client;

import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.clusterswisdom.horn.api.tmall.config.TmallApplication;
import com.taobao.api.TaobaoRequest;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.request.AlipaySystemOauthTokenRequest;
import com.taobao.api.response.AlipaySystemOauthTokenResponse;

public class HornAlipayClient extends DefaultAlipayClient implements TmClient {

	private TmallApplication application;
	
	public HornAlipayClient(TmallApplication application) {
		super(application.getUrl(), application.getAppKey(), application.getAppSecret());
		this.application = application;
	}
	
	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public TaobaoResponse execute(TaobaoRequest request, String session) throws AlipayApiException {
//		if (!HornTaobaoClient.sessionInvalidate(application)) {
//			try {
//				session = refreshSession();
//				
//			} catch (Exception e) {
//				e.printStackTrace();
//				
//			}
//		}
		
		return super.execute(request, session);
	}


	@Override
	public String initCode(String code) {
		AlipaySystemOauthTokenRequest req = new AlipaySystemOauthTokenRequest();
		req.setGrantType("authorization_code");
		req.setCode(code);
		try {
			AlipaySystemOauthTokenResponse response = execute(req);
			String token = response.getAccessToken();
			String refreshToken = response.getRefreshToken();
			Long expireIn = Long.parseLong(response.getExpiresIn());
			HornTaobaoClient.initApplication(this, token, refreshToken, expireIn);
			return "token:" + token + "; refreshToken:" + refreshToken + "; exireIn:" + expireIn;
			
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return e.getMessage();
			
		} 
	}
	
	private String refreshSession() throws AlipayApiException {
		AlipaySystemOauthTokenRequest req=new AlipaySystemOauthTokenRequest();
		// 用刷新令牌取授权令牌
		req.setGrantType("refresh_token");
		// 刷新令牌
		req.setRefreshToken(application.getRefreshKey());
		AlipaySystemOauthTokenResponse response = execute(req); 
		
		String token = response.getAccessToken();
		String refreshToken = response.getRefreshToken();
		Long expireIn = Long.parseLong(response.getExpiresIn());
		
		application.setSessionKey(token);
		application.setRefreshKey(refreshToken);
		application.setInvalidateTime(System.currentTimeMillis() + expireIn);
		
		return token;
	}

	@Override
	public TmallApplication getApplication() {
		return this.application;
	}
}